<template>
  <div>
    <el-card>
      <el-form :inline="true" class="form">
        <el-form-item label="用户名：">
          <el-input v-model="keyword" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="!keyword.length" @click="search"
            >搜索</el-button
          >
          <el-button type="primary"  @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-button type="primary" @click="addUser">添加用户数</el-button>
      <el-button
        type="danger"
        :disabled="!selectIdArr.length"
        @click="deleteSelectUser"
        >批量删除</el-button
      >
      <el-table
        :data="tableData"
        :border="true"
        @selection-change="selectionTableChange"
      >
        <el-table-column align="center" type="selection" />
        <el-table-column align="center" type="index" label="#" />
        <el-table-column align="center" prop="id" label="ID" />
        <el-table-column
          align="center"
          prop="username"
          label="用户名称"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          prop="roleName"
          label="用户角色"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          prop="createTime"
          label="创建时间"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          prop="updateTime"
          label="更新时间"
          show-overflow-tooltip
        />
        <el-table-column align="center" label="操作" width="300">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="User"
              @click="setRole(row)"
            >
              分配角色
            </el-button>
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="editUser(row)"
            >
              编辑
            </el-button>

            <el-popconfirm
              :title="`确定要删除${row.username}`"
              width="260px"
              @confirm="deleteUser(row)"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="Delete"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 7, 9]"
        :background="true"
        layout="prev, pager, next, jumper, ->, total, sizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="getHasUser"
      />
    </el-card>

    <el-drawer
      v-model="drawer"
      :title="userParams.id ? '编辑用户' : '新增用户'"
      direction="rtl"
    >
      <el-form :model="userParams" :rules="rules" ref="formRef">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="userParams.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input v-model="userParams.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
          <el-input v-model="userParams.password" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save"> 确定 </el-button>
      </template>
    </el-drawer>

    <el-drawer v-model="drawer1" title="分配角色" direction="rtl">
      <el-form :model="userParams" :rules="rules" ref="formRef">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="userParams.username" disabled autocomplete="off" />
        </el-form-item>
        <el-form-item label="角色列表" prop="name">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <el-checkbox-group
            v-model="useRole"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox v-for="(role, i) in allRole" :key="i" :label="role">
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="drawer1 = false">取消</el-button>
        <el-button type="primary" @click="confirmClick"> 确定 </el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import {
  reqUserInfo,
  reqAddOrUpdateUser,
  reqAllRole,
  reqSetUserRole,
  reqRemoveUser,
  reqSelectUser
} from '@/api/acl/user/index'
import type {
  Records,
  UserResponseData,
  User,
  AllRole,
  AllRoleResponseData,
  SetRoleData
} from '@/api/acl/user/type'
import { ElMessage } from 'element-plus'
import { ref, onMounted, reactive } from 'vue'
const tableData = ref<Records>([])
const pageNo = ref<number>(1)
const total = ref<number>(0)
const pageSize = ref<number>(5)

const getHasUser = async (pager = 1) => {
  pageNo.value = pager
  const result: UserResponseData = await reqUserInfo(
    pageNo.value,
    pageSize.value,
    keyword.value
  )
  tableData.value = result.data.records
  total.value = result.data.total
}
const handleSizeChange = () => {
  getHasUser()
}
onMounted(() => {
  getHasUser()
})
const drawer = ref<boolean>(false)
const addUser = () => {
  drawer.value = true
  delete userParams.id
  Object.assign(userParams, { username: '', password: '', name: '' })
  formRef.value?.clearValidate()
}
const editUser = (row: User) => {
  drawer.value = true
  Object.assign(userParams, row)
  formRef.value?.clearValidate()
}

const userParams = reactive<User>({
  username: '',
  password: '',
  name: ''
})
const save = async () => {
  await formRef.value.validate()

  await reqAddOrUpdateUser(userParams)
  drawer.value = false
  ElMessage({
    type: 'success',
    message: userParams.id ? '更新成功' : '添加成功'
  })
  window.location.reload()

  // getHasUser(userParams.id ? pageNo.value : 1)
}
const cancel = () => {
  drawer.value = false
}
const validatorUserName = (rule: any, value: string, callback: any) => {
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户名称至少输入五位'))
  }
}
const rules = {
  username: [{ required: true, validator: validatorUserName, trigger: 'blur' }],
  password: [
    { required: true, min: 6, message: '请至少输入6位密码', trigger: 'blur' }
  ],
  name: [{ required: true, message: '请输入昵称', trigger: 'blur' }]
}
const formRef = ref<any>()

const drawer1 = ref<boolean>(false)
const setRole = async (row: User) => {
  Object.assign(userParams, row)

  const resule: AllRoleResponseData = await reqAllRole(row.id as number)
  allRole.value = resule.data.allRolesList
  useRole.value = resule.data.assignRoles

  drawer1.value = true
}
const checkAll = ref<boolean>(false)
const isIndeterminate = ref<boolean>(true)
const handleCheckAllChange = (val: boolean) => {
  useRole.value = val ? allRole.value : []
  isIndeterminate.value = false
}
const allRole = ref<AllRole>([])
const useRole = ref<AllRole>([])

const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRole.value.length
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < allRole.value.length //设置不确定状态，仅负责样式控制
}

const confirmClick = async () => {
  const data: SetRoleData = {
    userId: userParams.id as number,
    roleIdList: useRole.value.map((item) => item.id as number)
  }
  await reqSetUserRole(data)

  ElMessage({
    type: 'success',
    message: '分配成功'
  })

  drawer1.value = false

  getHasUser(pageNo.value)
}

const deleteUser = async (row: User) => {
  await reqRemoveUser(row.id as number)
  ElMessage({
    type: 'success',
    message: '删除成功'
  })

  getHasUser(tableData.value.length > 1 ? pageNo.value : pageNo.value - 1)
}

const selectIdArr = ref<Records>([])
const selectionTableChange = (value: Records) => {
  selectIdArr.value = value
}
const deleteSelectUser = async () => {
  const idList = selectIdArr.value.map((item) => item.id as number)
  await reqSelectUser(idList)
  ElMessage({
    type: 'success',
    message: '删除成功'
  })
  getHasUser(
    tableData.value.length > idList.length ? pageNo.value : pageNo.value - 1
  )
}

const keyword = ref<string>('')
const search = () => {
  getHasUser()
  keyword.value = ''
}

import useLayoutSettingStore from '@/store/modules/setting'
const settingStore = useLayoutSettingStore()
const reset= ()=>{
  settingStore.updateRefresh()
}
</script>

<style scoped>
.form {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
